layui.use(['jquery', 'laytpl', 'form', 'laydate', 'exutil', 'extable', 'exconfig', 'infoLinkType', 'releaseRouter',
], function () {
	var $ = layui.$;
	var form = layui.form;
	var laydate = layui.laydate;
	var exutil = layui.exutil;
	var extable = layui.extable;
	var exconfig = layui.exconfig;
	var infoLinkType = layui.infoLinkType;
	var releaseRouter = layui.releaseRouter;

	var tree = {
		tag: 'table',
		selectedGroup: null,//当前选择
		init: function () {
			var that = this;
			this.initButtonEvent();
			// 获取栏目树
			infoLinkType.tree().then(function (res) {
				if (res && res.length > 0) {
					// datas.treeData = res;
					$('#group_tree').tree({
						data: res,
						lines: true,
						formatter: function (node) {
							return node.name
						},
						onSelect: function (e) {
							console.log(e)
							if (!that.selectedGroup || e.id !== that.selectedGroup.id) {
								that.selectedGroup = e;
								table.init();
							}
						},
						onLoadSuccess: function (node, data) {
							if (data.length > 0) {
								var rootNode = $("#group_tree").tree('getRoot')
									.target;
								$("#group_tree").tree("collapseAll").tree('expand',
									rootNode);
								var n = $('#group_tree').tree('find', data[0].id);
								$('#group_tree').tree('select', n.target);
							}
						}

					});
					// 删除tree图标
					that.dealTreeIcon();
				} else {
					$("#group_tree").text("暂无分组，请新增");
				}
			});
		},
		//按钮事件
		initButtonEvent: function () {
			var that = this;
			//搜索
			form.on('submit(treeSearch)', function (data) {
				infoLinkType.tree({
					data: data.field
				}).then(function (res) {
					if (res && res.length > 0) {
						$('#group_tree').tree('loadData', res);
						that.dealTreeIcon();
					} else {
						$('#group_tree').text("暂无分组，请新增")
					}
				});
				return false;
			});
			// 新增分组
			$('#addTreeNode').on('click', function () {
				var selectedNode = $('#group_tree').tree('getSelected');
				var detailUrl = releaseRouter.link.detail({
					"_optype": "add"
				});
				if (selectedNode) {
					detailUrl += "&id=" + selectedNode.id;
				}
				exutil.open({
					title: '新增分组',
					area: ['600px', '500px'],
					content: detailUrl
				});
			});
			// 编辑分组
			$('#editTreeNode').on('click', function () {
				var selectedNode = $('#group_tree').tree('getSelected');
				if (!selectedNode) {
					exutil.toast("请先选择分组");
					return;
				}
				exutil.open({
					title: '编辑分组',
					area: ['800px', '500px'],
					content: releaseRouter.link.detail({
						"_optype": "edit",
						"id": selectedNode.id
					})
				});
			});
			// 删除分组
			$('#delTreeNode').on('click', function () {
				var selectedNode = $('#group_tree').tree('getSelected');
				if (!selectedNode) {
					exutil.msg("请选择栏目，再进行删除");
					return;
				}
				exutil.confirm('确定删除所选分组吗？', function (index) {
					infoLinkType.remove({
						data: {
							"ids": selectedNode.id
						}
					}).then(function (res) {
						exutil.toast("删除成功");
						exutil.updateTabPage();
					})
					exutil.close(index);
				});
			});
			//搜索

		},
		//图标处理
		dealTreeIcon() {
			$('#group_tree').find("span.tree-icon").removeClass('tree-folder tree-file');
		},
	}
	tree.init();



	var table = {
		tag: 'table',
		tableCurrentPage: 1,
		//初始化
		init: function () {
			var that = this
			this.initDate();
			//渲染
			this.renderTable();
			//搜索按钮
			form.on('submit(searchBtn)', function (data) {
				exutil.updateTabTable(that.tag, null, 1, data.field);
				return false;
			});
			//表格：工具栏
			extable.on(`toolbar(${this.tag})`, function (obj) {
				switch (obj.event) {
					case 'add'://新增
						var sourceType = exutil.getCurrentPageType();
						var url = exconfig.baseUrl() + '/modules/accessManage/pages/blackCar/detail.html';
						var content = exutil.createUrlForCleanCache(url, {
							"sourceType": sourceType,
							"callBack": 'onAddByCallback',
							"isSelectAll": 'all'
						});
						exutil.open({
							title: "新增",
							area: ['1200px', '562px'],
							btn: ['提交', '重置'],
							content: content//详情页面地址
						});
						break;
					case 'del'://批量删除
						var checkStatus = extable.checkStatus(that.tag)
						that.onDelete(checkStatus.data)
						break;
					case 'export'://导出
						var data = form.val('filterForm');
						data.token = exutil.getCookie(exconfig.tokenKey);
						data = $.param(data);
						var url = exconfig.baseUrl() + '/api/info/news/flow/exportExcel?' + data
						window.open(url);
						// window.open(encodeURI(url));
						break;
				}
				return false;
			})
			//表格：操作列
			extable.on(`tool(${this.tag})`, function (obj) {
				var data = obj.data;
				var layEvent = obj.event;
				if (layEvent == "view") {
					var url = `/modules/app/pages/eXinSheng/flow/detail/detail.html?appCode=${data.wfAppCode}&procId=${data.wfProcID}&status=3&showLike=1`;
					console.log(data, url)
					exutil.openNewPage(url);
					// window.location.href = `.three/w.html?cateId=${data.cateId}&newsId=${data.newsId}`;//跳转二级
				}
				else if (layEvent == "delete") {
					that.onDelete([data])
				}
			});
			//表格：点击标题跳转详情
			$(`body`).on('click', '.item-link', function () {
				var event = $(this).data('event')
				$(this).closest('td').siblings().last().find(`a[lay-event="${event}"]`).click()
			})
			/* 刷新表格 使用
				exutil.toast("操作成功", null, function () {
					window.opener.updateTable();
					window.close();
				});

				兼容写法，缺点：不可用this.tag,需要将写死
				indow.updateTable = this.updateTable
			*/
			window.updateTable = () => {
				exutil.updateTabTable(this.tag);
			}
			//返回按钮
			$('.back-btn').on('click', function () {
				window.history.back();
			})
		},
		//初始化：时间方法
		initDate: function () {
			laydate.render({
				elem: '#date',
				type: 'datetime',
				range: true,
				ready: function (date) {
					$(".layui-laydate-footer [lay-type='datetime'].laydate-btns-time").click();
					$(".laydate-main-list-1 .layui-laydate-content li ol li:last-child").click();
					$(".layui-laydate-footer [lay-type='date'].laydate-btns-time").click();
				},
				done: function (value, date, endDate) {
					if (value == '') {
						$('#endDate').val('')
						$('#startDate').val('')
					}
					else {
						value = value.split(' - ')
						$('#startDate').val(value[0])
						$('#endDate').val(value[1])
					}
				},

			});
		},
		//渲染表格
		renderTable: function () {
			console.log('渲染时tag', this.tag)
			extable.render({
				elem: "#" + this.tag,
				url: "/api/info/link/tree",
				// height: 'auto',
				id: this.tag,
				page: true,
				loading: true,
				toolbar: "#toolbar",
				where: {
					treeId: tree.selectedGroup.id,
					title: $("#titleByAppraise").val(),
				},
				defaultToolbar: ["filter"],
				cols: [
					[
						/**
						 * 常用列宽
						 * 	时间：170
						 *  姓名：100
						 * 	两个字：60
						 */
						//{type: 'checkbox', fixed: 'left'},
						{ type: "numbers", width: 65, title: "序号", },
						{ field: "ip", title: "访问者IP", width: 150, },
						{ field: "cateName", title: "栏目名称", width: 150, },
						{
							field: "newsTitle",
							title: "文章标题",
							minWidth: 250,
							templet: function (d) {
								//data-event="view"，为lay-event="view"，根据需要调整
								return `<div class="item-link" data-event="view">${d.title}<div>`
							}
						},
						{ field: "createDate", title: "访问时间", width: 170 },
						{ field: "url", title: "访问地址", width: 250 },
						{
							field: "isVote",
							title: "是否投票",
							width: 90,
							templet: function (d) {
								var txt = "待提交";
								switch (d.isVote) {
									case 1: {
										txt = "已提交";
										break;
									}
								}
								return txt;
							},
						},
						//{ title: "操作", toolbar: "#rowbar", width: 130, fixed: "right", align: "center", },
					],
				],
				exdone: function (res, curr, count) {
					// 设置当前页码
					this.tableCurrentPage = curr;
				},
			});
		},
		//事件-删除
		onDelete: function (list) {
			var that = this
			var tips = list.map(v => {
				return v.personnelName
			}).toString()
			var ids = list.map(v => {
				return v.id
			}).toString()
			if (ids == '') {
				exutil.msg("请选择数据，再进行删除");
				return
			}
			exutil.confirm('确定<b class="red">' + tips + '</b>删除吗？', function (index) {
				var opts = {
					data: {
						ids: ids
					}
				}
				exutil.post('/api/black/user/delete', opts).then(function (res) {
					exutil.toast("操作成功");
					exutil.updateTabTable(that.tag);
					exutil.close();
				});
			});

		},
	};

});
